/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.pigeon.utils;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.seppiko.commons.utils.Base64Util;
import org.seppiko.pigeon.configuration.PigeonConfiguration;
import org.seppiko.pigeon.exceptions.PigeonException;
import org.seppiko.pigeon.exceptions.PigeonHashException;

/**
 * Password Encoding/Decoding Util
 *
 * @author Leonard Woo
 */
@Slf4j
public class PasswordUtil {

  private static PigeonConfiguration config = PigeonConfiguration.getInstance();

  private static byte[] salt;
  private static byte[] iv;

  static {
    salt = Base64Util.decode(config.getSalt());
    iv = Base64Util.decode(config.getIv());
  }

  public static String encode(String data, String password) {
    try {

      return Base64Util.encodeToString(
          AesUtil.encode(
              data.getBytes(StandardCharsets.UTF_8), hash(password), iv) );
    } catch (PigeonException e) {
      log.error("", e);
    }
    return null;
  }

  public static String decode(String data, String password) {
    try {
      return StandardCharsets.UTF_8.decode(
          ByteBuffer.wrap(
              AesUtil.decode(
                  Base64Util.decode(data), hash(password), iv ) ) ).toString();
    } catch (PigeonException e) {
      log.error("", e);
    }
    return null;
  }

  public static byte[] hash(String data) throws PigeonHashException {
    return HashUtil.pbkdf2HmacSHA512(data, salt);
  }
}
